﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using RazakiBLL;
using RazakiBLL.Entities;

namespace RazakiSite.UserControls
{
    public partial class UCPayEdit : BaseUserControl
    {
        private UowRazaki uowRazaki = new UowRazaki();

        protected void Page_Load(object sender, EventArgs e)
        {
            if (IsPostBack)
                return;

            ConfigControls();
        }

        private void ConfigControls()
        {
            var banks = uowRazaki.BankRepository.GetAllSorted();

            DdlBanks.QuickBind(banks, "Description", "Id");
            DdlBanks.InsertDefaultItem();

            //<reset all

            ClearControls();

            //می توان اطلاعات مربوط به ایمیل و تلفن را نیز وارد کرد
            if (UtilitiesUI.CurrentContactIsUser())
            {
                Guid userId = UtilitiesUI.GetCurrentUserId();

                TxtName.Text = UtilitiesUI.GetFullNameOfUser(userId);
            }

            //>
        }

        protected void BtnSend_Click(object sender, EventArgs e)
        {
            string message;
            if (!ValidateControls(out message))
            {
                UCInfoResult.Text = message;
                UCInfoResult.InfoType = EInfoType.error;
                UCInfoResult.Hide = false;

                return;
            }

            UowRazaki uowRazaki = new UowRazaki();

            string name = TxtName.Text;
            string email = TxtEmail.Text;
            string phone = TxtPhone.Text;
            short bankId = short.Parse(DdlBanks.SelectedValue);
            DateTime paymentDate = ClnPaymentDate.GetGregorian().Value;
            int paymentAmount = int.Parse(UtilitiesBLL.RawNumber(txtPaymentAmount.Text));
            string text = TxtText.Text;

            Payment payment = new Payment
                                  {
                                      Person = new Person
                                      {
                                          Name = name,
                                          Email = email,
                                          Phone = phone
                                      },
                                      BankId = bankId,
                                      PaymentDate=paymentDate,
                                      PaymentAmount = paymentAmount,
                                      Text = text,
                                      LastUpdatedDate = DateTime.Now
                                  };

            if (UtilitiesUI.CurrentContactIsUser())
                payment.UserId = UtilitiesUI.GetCurrentUserId();

            uowRazaki.PaymentRepository.Add(payment);
            if (uowRazaki.Save() > 0)
            {
                UCInfoResult.Text = UtilitiesUI.Sentences(ESentences.success);
                UCInfoResult.InfoType = EInfoType.success;

                SendMessage();

                ConfigControls();
            }
            else
            {
                UCInfoResult.Text = UtilitiesUI.Sentences(ESentences.error);
                UCInfoResult.InfoType = EInfoType.error;
            }

            UCInfoResult.Hide = false;

        }

        private void SendMessage()
        {
            if (!string.IsNullOrWhiteSpace(TxtEmail.Text))
            {
                string name = " ";
                string[] mails = new[] {TxtEmail.Text};

                if (!string.IsNullOrWhiteSpace(TxtName.Text))
                    name = string.Format(" آقای/خانم {0} ", TxtName.Text);

                UtilitiesUI.SendEmailForRequest(name, mails);
            }
        }

        private bool ValidateControls(out string message)
        {
            string name = TxtName.Text;
            //اگر هم ایمیل و هم شماره تلفن خالی باشند پیغام داده شود
            string email = TxtEmail.Text;
            string phone = TxtPhone.Text;
            short bankId = short.Parse(DdlBanks.SelectedValue);
            DateTime? paymentDate = ClnPaymentDate.GetGregorian();
            string paymentAmount = UtilitiesBLL.RawNumber(txtPaymentAmount.Text);
            int intPaymentAmount;
            string text = TxtText.Text;

            message = string.Empty;

            if (string.IsNullOrWhiteSpace(name))
            {
                message = string.Format(UtilitiesUI.Sentences(ESentences.requiredFill), "نام و نام خانوادگی");
                return false;
            }

            if (string.IsNullOrWhiteSpace(email) && string.IsNullOrWhiteSpace(phone))
            {
                message = "لطفاً حداقل یکی از فیلدهای پست الکترونیکی و شماره تلفن را پر نمایید";
                return false;
            }

            if (bankId < 0)
            {
                message = string.Format(UtilitiesUI.Sentences(ESentences.requiredSelect), "بانک مربوطه");
                return false;
            }

            if (!paymentDate.HasValue)
            {
                message = string.Format(UtilitiesUI.Sentences(ESentences.incorect), "تاریخ واریز");
                return false;
            }

            if (!string.IsNullOrWhiteSpace(paymentAmount))
            {
                if (!int.TryParse(paymentAmount, out intPaymentAmount))
                {
                    message = string.Format(UtilitiesUI.Sentences(ESentences.incorect), "مبلغ واریز");
                    return false;
                }
            }
            else
            {
                message = string.Format(UtilitiesUI.Sentences(ESentences.requiredSelect), "مبلغ واریز");
                return false;
            }

            if (string.IsNullOrWhiteSpace(text))
            {
                message = string.Format(UtilitiesUI.Sentences(ESentences.requiredFill), "توضیحات تکمیلی");
                return false;
            }

            return true;
        }

        private void ClearControls()
        {
            TxtName.Text =
                TxtEmail.Text =
                TxtPhone.Text =
                ClnPaymentDate.Text =
                txtPaymentAmount.Text =
                TxtText.Text = string.Empty;
        }
    }
}